import { Component, ElementRef, EventEmitter, Input, OnInit, Output, SimpleChange, TemplateRef, ViewChild } from '@angular/core';

@Component({
  selector: 'app-paginator',
  templateUrl: './paginator.component.html',
  styleUrls: ['./paginator.component.scss'],
})

export class PaginatorComponent implements OnInit {

  public pageValue = 1;
  @Input() page = 1; // 传入用户点击的页数
  @Input() total: number; // 数据总个数
  @Input() selectedLimit: number; // 每页展示的数据个数
  @Input() limitOptions: any[]; // limit options

  @Output() goPrev = new EventEmitter(); // 跳转上一页
  @Output() goNext = new EventEmitter(); // 跳转下一页
  @Output() goPage = new EventEmitter(); // 初始化页面
  @Output() goFirst = new EventEmitter(); // 跳转首页
  @Output() goLast = new EventEmitter(); // 跳转尾页
  @Output() goSelect = new EventEmitter(); // 设置父组件selectLimit
  @Output() doFunction: EventEmitter<any> = new EventEmitter();

  constructor(private elementRef: ElementRef) {
    // console.log(this.elementRef.nativeElement.value);
  }

  ngOnChanges(changes: {[propKey: string]: SimpleChange}) {

  }

  ngOnInit() {

  }

  // 选择limit后重绘页面
  setLimit($event) {
    this.page = this.pageValue = 1;
    console.log('分页=-------' + this.selectedLimit);
    this.goSelect.emit(this.selectedLimit);
    this.goPage.emit({num: this.page, limit: this.selectedLimit});
  }

  onPage($event): void {
     this.goPage.emit({num: $event.num, limit: $event.limit});
  }
  onPrev(): void {
    console.log(this.page);
    console.log(this.selectedLimit);
    if (parseInt(this.page as unknown as string) - 1 > Math.ceil(this.total / this.selectedLimit)) {return; }
    this.page = this.pageValue = parseInt(this.page as unknown as string) - 1;
    this.goPrev.emit({num: this.page, limit: this.selectedLimit});
  }

  onNext(): void {
    if (parseInt(this.page as unknown as string) + 1 > Math.ceil(this.total / this.selectedLimit)) {return; }
    this.page = this.pageValue = parseInt(this.page as unknown as string) + 1;
    this.goNext.emit({num: this.page, limit: this.selectedLimit});
  }
  onFirst(): void {
    this.page = this.pageValue = 1;
    this.goFirst.emit({num: this.page, limit: this.selectedLimit});
  }
  onLast(): void {
    this.page = this.pageValue = Math.ceil(this.total / this.selectedLimit);
    this.goFirst.emit({num: this.page, limit: this.selectedLimit});
  }
  // set selecitLimit
  // 鼠标离开事件
  onSetPageValue(num) {
    this.pageValue = num;
  }
  onBlur($event): void {
      if (this.pageValue > Math.ceil(this.total / this.selectedLimit)) {return; }
      this.page = this.pageValue;
      console.log('鼠标离开');
      console.log(this.pageValue + '--------' + this.selectedLimit);
      this.onPage({num: this.pageValue, limit: this.selectedLimit});
  }
}
